package com.uniq.qr;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import com.uniq.db.ConnectionFactory;
import com.uniq.qr.QRCode;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * Servlet implementation class GenerateQr
 */
@WebServlet("/GenerateQr")
public class GenerateQr extends HttpServlet {
	private static final long serialVersionUID = 1L;
        File file ;
        String filePath =new String();
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GenerateQr() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out=response.getWriter();
		response.setContentType("image/jpg");
		String supplier=request.getParameter("supplier");
		request.setAttribute("supplier",supplier);
		String brand=request.getParameter("brand");
		request.setAttribute("brand",brand);
		String size=request.getParameter("size");
		request.setAttribute("size",size);
		String color=request.getParameter("color");
		request.setAttribute("color",color);
		String article_no=request.getParameter("article_no");
		request.setAttribute("article_no",article_no);
		String cost_price=request.getParameter("cost_price");
		request.setAttribute("cost_price",cost_price);
		String selling_price=request.getParameter("selling_price");
		request.setAttribute("selling_price",selling_price);
		
		String data="supplier:"+supplier+",brand:"+brand+",size:"+size+",color:"+color+",article_no:"+article_no+",cost_price:"+cost_price+",selling_price:"+selling_price;
		
		String query="insert into stock(supplier,brand,size,color,article_no,cost_price,selling_price) values "
				+ "('"+supplier+"','"+brand+"','"+size+"','"+color+"','"+article_no+"','"+cost_price+"','"+selling_price+"')";
		
		System.out.println(query);
		Connection c =ConnectionFactory.getConnection();
		String path=getServletContext().getRealPath("/images");
              
		try {
			QRCode.generate(data, path);
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                
		
		RequestDispatcher rd=request.getRequestDispatcher("AddStock.jsp");
		rd.forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        {
	
		
		PrintWriter out=response.getWriter();
		Connection c=ConnectionFactory.getConnection();
                DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */
    String path=getServletContext().getRealPath("/images");
                    filePath=path+"/";
 String supplier=new String();
 String brand=new String();
String size=new String();
String color=new String();
String article_no=new String();
String cost_price=new String();
String selling_price=new String();
String description=new String();
 String branch=new String();
  String stock_count=new String();
File repositoryPath = new File(filePath);//"/temp");
diskFileItemFactory.setRepository(repositoryPath);

ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(1000000);
try {
     List  items = servletFileUpload.parseRequest(request);
                Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (item.isFormField()) {


        if(item.getFieldName().equals("supplier"))
        {
         supplier=item.getString();
        }
                if(item.getFieldName().equals("brand"))
        {
         brand=item.getString();
        }
        if(item.getFieldName().equals("size"))
        {
         size=item.getString();
        }    
            if(item.getFieldName().equals("color"))
        {
         color=item.getString();
        }    
        if(item.getFieldName().equals("article_no"))
        {
         article_no=item.getString();
        }    
           if(item.getFieldName().equals("cost_price"))
        {
         cost_price=item.getString();
        }   
               if(item.getFieldName().equals("selling_price"))
        {
         selling_price=item.getString();
        }    
           if(item.getFieldName().equals("description"))
        {
         description=item.getString();
        }    
                 if(item.getFieldName().equals("branch"))
        {
         branch=item.getString();
        }  
    if(item.getFieldName().equals("stock_count"))
        {
         stock_count=item.getString();
        }      
			//String brand=request.getParameter("brand");
			
		//	String size=request.getParameter("size");
			
			//String color=request.getParameter("color");
			
			//String article_no=request.getParameter("article_no");
			
		//	String cost_price=request.getParameter("cost_price");
			
			//String selling_price=request.getParameter("selling_price");
			
			
                        
      String name = item.getFieldName();//text1
      String value = item.getString();

    } else {
        processUploadedFile(item);
    }
    
    
   
    
}
        String filePath=getServletContext().getRealPath("/images")+"\\QRCode.png";
		//	String filePath="D:/QRCode.png";
 
     String id=getID();
     int i=Integer.parseInt(id);
     i++;
        String data="id:"+i+",supplier:"+supplier+",brand:"+brand+",size:"+size+",color:"+color+",article_no:"+article_no+",cost_price:"+cost_price+",selling_price:"+selling_price;
              
		try {
			QRCode.generate(data, path);
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}      
                	FileInputStream  inputStream = new FileInputStream(new File(filePath));
                        FileInputStream  inputStream1 = new FileInputStream(file);
			String query="insert into stock(supplier,brand,size,color,article_no,cost_price,selling_price,qrcode,product_image,description,branch,stock_count,id) values "
					+ "(?,?,?,?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement s=c.prepareStatement(query);
			s.setString(1,supplier);
			s.setString(2,brand);
			s.setString(3,size);
			s.setString(4,color);
			s.setString(5,article_no);
			s.setDouble(6,Double.parseDouble(cost_price));
			s.setDouble(7,Double.parseDouble(selling_price));
			s.setBinaryStream(8,inputStream,inputStream.available());
			s.setBinaryStream(9,inputStream1,inputStream1.available());
                        s.setString(10,description);
                        s.setString(11,branch);
                        s.setString(12,stock_count);
                        s.setInt(13,i);
			s.executeUpdate();
                        new File(filePath).delete();
                        RequestDispatcher rd=request.getRequestDispatcher("AdminHeader.jsp");
                        rd.include(request, response);
			out.println("<h1>Stock added successfully</h1>");
			out.println("<a href='ViewStock.jsp'>View Stock</a>");
			out.println("<a href='AddStock.jsp'>Again add Stock details</a>");		
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

    private void processUploadedFile(FileItem item) 
    {
        try {
            String fieldName = item.getFieldName();
               String fileName = item.getName();
               boolean isInMemory = item.isInMemory();
               long sizeInBytes = item.getSize();
               // Write the file
               if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath+fileName.substring( fileName.lastIndexOf("\\"))) ;
               }else{
               file = new File( filePath+fileName.substring(fileName.lastIndexOf("\\")+1)) ;
               }
               System.out.println(file.getAbsolutePath());
               item.write(file) ;
        } catch (Exception ex) {
            Logger.getLogger(GenerateQr.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String getID() {
        String id=new String();
        try {
            Connection con=ConnectionFactory.getConnection();
            Statement st1=con.createStatement();
          ResultSet rs=st1.executeQuery("SELECT * FROM STOCK");
          while(rs.next())
          {
              id=rs.getString("id");
          }
            
        } catch (SQLException ex) {
            Logger.getLogger(GenerateQr.class.getName()).log(Level.SEVERE, null, ex);
        }
        return id;
    }

}
